package com.QK.cnstudy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.QK.cnstudy.adapter.TextBookAdapter;
import com.QK.cnstudy.db.DBManager;
import com.QK.cnstudy.entity.Term;

public class TermActivity extends Activity implements OnItemClickListener, OnClickListener {

    DBManager dbManager = null;
    private TextBookAdapter adapter;
    private ListView listView = null;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Button backButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.term);

        dbManager = CnStudyApp.app.dbManager;
        getView();
        setListViewData();
        adapter = new TextBookAdapter(this, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        backButton.setOnClickListener(this);
    }

    public void setListViewData() {
        List<Term> terms = dbManager.getTerms();

        for (Term term : terms) {

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", term.getId());
            map.put("name", term.getName());
            list.add(map);
        }
    }

    public void getView() {
        listView = (ListView) findViewById(R.id.term_list);
        backButton = (Button) findViewById(R.id.back);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Map<String, Object> map = list.get(arg2);
        String title = (String) map.get("name");
        int termId = (Integer) map.get("id");
        Intent intent;
        Bundle bundle = new Bundle();
        bundle.putInt("term_id", termId);
        bundle.putInt("textbook_id", 1);
        intent = new Intent(this, WorkSelectActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {

        Intent intent;
        switch (v.getId()) {
        case R.id.back:

            onBackPressed();
            break;

        default:
            break;
        }

    }
}